package me.huanmeng.heater.sender.manager;

import cn.hutool.json.JSONObject;
import cn.hutool.json.JSONUtil;
import com.google.common.collect.Lists;
import me.huanmeng.heater.exception.ResponseException;
import me.huanmeng.heater.http.KaiheilaApi;
import me.huanmeng.heater.main.HeaterMain;
import me.huanmeng.heater.object.Guild;
import org.jetbrains.annotations.Nullable;

import java.util.Collection;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

/**
 * 2021/10/4<br>
 * Heater<br>
 *
 * @author huanmeng_qwq
 */
public class GuildManager {
    private final Map<String, Guild> guilds;

    public GuildManager() {
        guilds = new HashMap<>();
        init();
    }


    public void init() {
        for (Guild guild : getGuildsHttp()) {
            update(guild);
        }
    }

    public Collection<Guild> getGuilds(){
        return guilds.values();
    }
    @Nullable
    public Guild getGuild(String id){
        return guilds.get(id);
    }
    public void update(Guild guild) {
        if (guilds.containsKey(guild.getId())) {
            final Guild g = guilds.get(guild.getId());
            g.setId(guild.getId());
            g.setName(guild.getName());
            g.setTopic(guild.getTopic());
            g.setMaster_id(guild.getMaster_id());
            g.setIcon(guild.getIcon());
            g.setNotify_type(guild.getNotify_type());
            g.setRegion(guild.getRegion());
            g.setEnable_open(guild.isEnable_open());
            g.setOpen_id(guild.getOpen_id());
            g.setDefault_channel_id(guild.getDefault_channel_id());
            g.setWelcome_channel_id(guild.getWelcome_channel_id());
            g.setBoost_num(guild.getBoost_num());
            g.setLevel(guild.getLevel());
        } else {
            guilds.put(guild.getId(), guild);
        }
    }

    List<Guild> getGuildsHttp() {
        return getGuilds(1);
    }

    List<Guild> getGuilds(int page) {
        List<Guild> guildlist = Lists.newArrayList();
        final KaiheilaApi kaiheilaApi = HeaterMain.getInstance().getKaiheilaApi();
        final String body = kaiheilaApi.doGet("/guild/list")
                .form("page", page)
                .form("page_size", 20)
                .executeAsync().body();
        final JSONObject jsonObject = new JSONObject(body);
        if (jsonObject.getInt("code", -1) != 0) {
            throw new ResponseException(body);
        }
        for (Object o : jsonObject.getJSONObject("data").getJSONArray("items")) {
            guildlist.add(JSONUtil.toBean((JSONObject) o, Guild.class));
        }
        if (jsonObject.getJSONObject("data").getJSONObject("meta").getInt("page_total", page) > page) {
            guildlist.addAll(getGuilds(page + 1));
        }
        return guildlist;
    }

}
